import React from 'react'
import {Button, Card, DatePicker, Form, Input, message, Modal, Select, Table} from 'antd'
import {fetchPost} from './../../../utils/request'

const FormItem = Form.Item
const {RangePicker} = DatePicker
const dateFormat = 'YYYY-MM-DD'

class Index extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isAddToModal: false,
      manualOrderList: [],
      orderInfo: null,
      accountList: [],
      record: null,//record 当前行对象
      loading: false,
      page: {
        currentPage: 1,
        pageSize: 13,
        totalCount: 0
      },
      tradeNo: '',
      startDate: '',
      endDate: ''
    }
  }

  componentDidMount() {
    this.getData();
  }

  handleSearch = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const {tradeNo, transferDateTime} = values
        this.setState({
            tradeNo: tradeNo,
            transferDateTime: transferDateTime
          }, () => {
            this.getData()
          }
        )
      }
    })
  }

  handleCancel = () => {
    this.setState({
      isAddToModal: false
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let {assignTradeNo, account} = values
        let param = {
          tradeNo: assignTradeNo,
          account
        }
        fetchPost('/collection/order/manual/distribute', param).then(json => {
          if (json.code === 0) {
            message.info('success', 0.5, () => {
              this.setState(
                {
                  isAddToModal: false
                }, () => {
                  this.getData()
                }
              );
              this.props.form.resetFields()
            });
          } else {
            message.error(json.msg, 2, () => {
              this.setState({
                isAddToModal: false
              })
            })
          }
        })

      }
    })
  }

  getData() {
    let self = this
    this.setState({
      loading: true
    }, () => {
      fetchPost(`/collection/order/manual/list?currentPage=${self.state.page.currentPage}&pageSize=${self.state.page.pageSize}`, {
        tradeNo: this.state.tradeNo,
        startDate: this.state.startDate,
        endDate: this.state.endDate
      }).then(res => {
        if (res.code === 0) {
          let manualOrderList = res.data.manualOrderList
          if (manualOrderList) {
            this.setState({
              manualOrderList: manualOrderList,
              loading: false
            })
          } else {
            this.setState({
              manualOrderList: [],
              loading: false
            })
          }
        } else {
          this.setState({
            loading: false
          }, () => {
            message.warn(res.msg)
          })
        }
      })
    })
  }

  getCollectionAdmin(record) {
    let repayDate = record.repayDate
    let assignTradeNo = record.tradeNo
    fetchPost('/collection/role/admin/query', {repayDate: repayDate}).then(json => {
      if (json.code === 0) {
        this.setState({
          accountList: json.data.accountList,
          record: record,
          isAddToModal: true
        })
      }
    })
  }

  changeTime(time) {
    if (time.length) {
      let startDate = time[0].format(dateFormat)
      let endDate = time[1].format(dateFormat)
      this.setState({
        startDate: startDate,
        endDate: endDate
      })
    } else {
      this.setState({
        startDate: '',
        endDate: ''
      })
    }
  }

  render() {

    const formItemLayout = {labelCol: {span: 8}, wrapperCol: {span: 16},}

    const {getFieldDecorator} = this.props.form

    const columns = [
      {
        title: 'No',
        dataIndex: 'index',
        key: 'index',
      }, {
        title: 'User Name',
        dataIndex: 'userName',
        key: 'userName',
      }, {
        title: 'LoanId',
        dataIndex: 'tradeNo',
        key: 'tradeNo',
      }, {
        title: 'Amount',
        dataIndex: 'amount',
        key: 'amount',
      }, {
        title: 'Duration',
        dataIndex: 'duration',
        key: 'duration',
      }, {
        title: 'Repay Date',
        dataIndex: 'repayDate',
        key: 'repayDate',
      }, {
        title: 'Transfer date time',
        dataIndex: 'transFerDateTime',
        key: 'transFerDateTime',
      }, {
        title: 'Current Stage',
        dataIndex: 'currentStage',
        key: 'currentStage',
      }, {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
      }, {
        title: 'pre-collection auditor',
        dataIndex: 'auditor',
        key: 'auditor',
      }, {
        title: 'User language',
        dataIndex: 'userLanguage',
        key: 'userLanguage',
      },
      {
        title: 'Operation',
        key: 'action',
        render: (text, record) => {
          return (
            record.inBlackList === true ? null
              : <Button type="danger"
                        onClick={() => this.getCollectionAdmin(record)}
              >Assign</Button>
          )
        },
      }
    ]

    return (
      <div>

        <Modal title="Assign" visible={this.state.isAddToModal} onCancel={this.handleCancel} footer={null}>
          <Form style={{margin: 'auto'}} horizontal>
            <FormItem {...formItemLayout} label="Loan ID">
              {getFieldDecorator('assignTradeNo', {initialValue: this.state.record == null ? '' : this.state.record.tradeNo})(
                <Input disabled/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="User language">
              {this.state.record == null ? <div></div> :
                <div>{this.state.record.userLanguage}</div>}
            </FormItem>
            <FormItem {...formItemLayout} label="Pre-collection auditor">
              {this.state.record == null ? <div></div> :
                <div>{this.state.record.auditor}</div>}
            </FormItem>
            <FormItem {...formItemLayout} label="New-collection auditor">
              {getFieldDecorator('account', {
                rules: [{required: true}],
                initialValue: ''
              })(
                <Select placeholder='请选择' style={{width: 100}}>
                  {
                    this.state.accountList.map((item) => {
                      return (<Option key={item.key} value={item.value}>{item.key}</Option>)
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem wrapperCol={{span: 12, offset: 5}}>
              <Button type="primary" onClick={e => this.handleSubmit(e)}>OK</Button>
              <Button style={{marginLeft: 16}} type="ghost" onClick={this.handleCancel}>Cancel</Button>
            </FormItem>
          </Form>
        </Modal>

        <Form layout='inline' className='mb20'>
          <FormItem label='LoanId' hasFeedback>
            {getFieldDecorator('tradeNo', {
              initialValue: '',
            })(
              <Input/>
            )}
          </FormItem>

          <FormItem label='Transfer date time' hasFeedback>
            {getFieldDecorator('transferDateTime', {initialValue: ''})(
              <RangePicker onChange={(e) => {
                this.changeTime(e)
              }} allowClear={false}/>
            )}
          </FormItem>

          <FormItem>
            <Button type='primary' onClick={e => this.handleSearch(e)}>Search</Button>
          </FormItem>
        </Form>

        <Card>
          <Table
            columns={columns}
            dataSource={this.state.manualOrderList}
            loading={this.state.loading}
            pagination={false}/>
        </Card>

      </div>
    )
  }

}

Index = Form.create()(Index)
export default Index
